package com.itheima.reggie.controller;


import cn.hutool.core.io.IoUtil;
import com.alibaba.druid.util.Utils;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;


@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;

    /*
     * 文件上传
     * */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        log.info("file:{}", file);
        //获得原先文件名
        String filename = file.getOriginalFilename();
        filename = filename.substring(filename.lastIndexOf("."));
        log.info("文件的后缀名为：" + filename);
        String name = UUID.randomUUID().toString();
        filename = name + filename;
        //创建目录对象
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //将文件存储到本地
        try {
            file.transferTo(new File(basePath + filename));
        } catch (IOException e) {
            e.printStackTrace();

        }
        return R.success(filename);
    }

    /*
     * 文件下载
     * */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {
            // 强制要求浏览器下载
            response.setHeader("Content-Disposition", "attachment; filename=" + name);
            //输入流读取文件
            FileInputStream fileInputStream = new FileInputStream(new File(basePath+File.separator+name));
            //获取响应输出流
            ServletOutputStream outputStream = response.getOutputStream();
            IoUtil.copy(fileInputStream, outputStream);
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
